package com.qianji.petmall.product.exception;

import com.qianji.common.exception.BizCodeEnum;
import com.qianji.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;

/**
 * @author liang zai
 * @date 2022/1/17 14:44
 * @description
 * 统一的异常处理类
 */
@Slf4j
//@ControllerAdvice()
@RestControllerAdvice(basePackages = "com.qianji.petmall.product.controller")
public class PetmallExceptionCotrollerAdvice {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e){
      log.error("数据检验出现问题{}，异常类型：{}",e.getMessage(),e.getClass());
        BindingResult result = e.getBindingResult();
        HashMap<String, Object> map = new HashMap<>();
        result.getFieldErrors().forEach((fieldError)->{
            //获取错误的属性名
            String field = fieldError.getField();
            //获取到错误的信息
            String message = fieldError.getDefaultMessage();
            map.put(field,message);
        });
        return R.error(BizCodeEnum.VALID_EXCEPTION.getCode(),BizCodeEnum.VALID_EXCEPTION.getMsg()).put("data",map);
    }
//    @ExceptionHandler(value = Throwable.class)
//    public R handleException(Throwable e){
//        log.error("数据检验出现问题{}，异常类型：{}",e.getMessage(),e.getClass());
//        return R.error(BizCodeEnum.UNKNOW_EXCEPTION.getCode(),BizCodeEnum.UNKNOW_EXCEPTION.getMsg());
//    }
}
